<template>
  <div class="page-mobile-coupon">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      title="优惠卷"
    ></white-header>
    <div class="menu-list">
      <div :class="['menu-item',action == 1 ? 'active' : '']" @click="menuHandle(1)">未使用</div>
      <div :class="['menu-item',action == 2 ? 'active' : '']" @click="menuHandle(2)">已使用</div>
      <div :class="['menu-item',action == 3 ? 'active' : '']" @click="menuHandle(3)">已过期</div>
    </div>
    <div class="coupon-list">
      <div class="coupon-box" :class="[action == 1 ? 'bg-one' : action == 2 ? 'bg-two': action == 3 ? 'bg-three':'']" v-for="(item,index) in showCouponList" :key="index">
        <div class="tags">
          <span>{{item.couponType == 1 ? '无门槛':'满减卷'}}</span>
          |
          <span>{{item.couponGoodType == 1 ? '全课通用':'指定课程'}}</span>
        </div>
        <div class="card-left">
          ￥<span class="price">{{item.couponAmount}}</span>
          <div class="right-line"></div>
        </div>
        <div class="card-right">
          <div class="max-time">
            <span v-if="item.couponType == 0">满{{item.conditionalAmount}}可用</span>
            <span v-if="item.couponType == 1">无门槛</span>
          </div>
          <div class="course-name" v-if="item.couponGoodType != 1">限《{{item.id | formatCourseName(that)}}》课程使用</div>
          <div class="info-time">有效期至 {{formatDate(item.endTime)}}</div>
        </div>
      </div>
    </div>
    <!-- <div class="footer" v-show="couponList.length != 0">
      <span class="tips">我是有底线的</span>
    </div> -->
    <!-- <van-empty
      description="暂时没有优惠卷哟~"
      v-show="couponList.length == 0"
    /> -->
  </div>
</template>

<script>
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import {getUserCoupon} from "~/api/coupon";
import {getCourse} from "~/api/course";
import { mapState, mapActions, mapMutations } from "vuex";
export default {
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    WhiteHeader
  },
  data() {
    return {
      that:this,
      action:1,
      couponList:{},//优惠卷列表
      allCourseList:[],//所有课程
      // couponPages: {
      //   page: 1,
      //   pageSize: 10,
      //   total: 0
      // }
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      is_ios(state) {
        return state.is_ios;
      },
      is_in_wechat(state) {
        return state.is_in_wechat;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      is_loading(state) {
        return state.is_loading;
      },
      is_wechat_ios_limit(state) {
        return state.is_wechat_ios_limit;
      }
    }),
    is_show_price() {
      if (this.is_wechat_ios_limit) {
        return this.is_ios && this.is_in_wechat;
      } else {
        return false;
      }
    },
    is_allow() {
      if (!this.recharge_num) {
        return false;
      } else {
        return true;
      }
    },
    active_query() {
      return this.$route.query.active;
    },
    num() {
      return this.$route.query.num;
    },
    redirect_url() {
      return this.$route.query.rdurl;
    },
    showCouponList(){
      let couponArr = [];
      let {currentCoupon,usrCoupon,outCoupon} = this.couponList;
      if(this.action == 1 && currentCoupon){
        couponArr = currentCoupon.reverse();
      }else if(this.action == 2 && usrCoupon){
        couponArr = usrCoupon.reverse();
      }else if(this.action == 3 && outCoupon){
        couponArr = outCoupon.reverse();
      }
      return couponArr;
      
    },
    
  },
  watch: {},
  filters:{
    formatCourseName(id,that){
      let courseObj = that.allCourseList.find(item=>item.id == id);
      console.log(that.allCourseList);
      console.log(courseObj);
      if(courseObj && Object.keys(courseObj).length > 0){
        return courseObj.courseName;
      }else{
        return "未知课程";
      }
    }
  },
  destroyed() {
    window.removeEventListener("scroll", this.eventListener);
    this.setDisabled(true);
  },
  deactivated() {
    window.removeEventListener("scroll", this.eventListener);
    this.setDisabled(true);
  },
  activated() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
        return;
      }
      window.addEventListener("scroll", this.eventListener);
    }
    this.couponPages = {
      page: 1,
      pageSize: 10,
      total: 0
    };
    this.getCouponList();
    this.setDisabled(false);
    this.refreshFun(() => {
      this.couponPages = {
        page: 1,
        pageSize: 10,
        total: 0
      };
      this.getCouponList();
      this.setLoading(false);
    });
  },
  methods: {
    ...mapActions([]),
    ...mapMutations(["SET_IS_LOADING"]),
    menuHandle(action){
      this.action = action;
    },
    formatDate(date) {
      var date = new Date(date);
      var YY = date.getFullYear() + "-";
      var MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hh =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var ss =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + " " + hh + mm + ss;
    },
    async getCouponList(){
      let result = await getUserCoupon(this.user_info.id);
      if(result && result.data && result.data.code == 200){
        this.couponList = result.data.data;
      }else{
        this.$toast("获取失败！");
      }
      // console.log("我的优惠卷",result);
    },
    async getCourse(){
      let result = await getCourse();
      if(result && result.data && result.data.code == 200){
        this.allCourseList = result.data.data.rows;
      }else{
        this.$toast("获取失败！");
      }
      // console.log("我的优惠卷",result);
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      if (scrollTop + clientHeight >= scrollHeight - 120) {
        console.log("上拉加载");
        if (
          this.couponPages.total <= this.couponList.length
        ) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.couponPages.page++;
        this.getCouponList("pullup");
      }
    },
    eventListener() {
      this.throttle(this.pullUp, 30);
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function() {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    }
  },
  created() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
        return;
      }
    }
    this.couponPages = {
      page: 1,
      pageSize: 10,
      total: 0
    };
    this.getCouponList();
    this.getCourse();
    this.setDisabled(false);
    this.refreshFun(() => {
      this.couponPages = {
        page: 1,
        pageSize: 10,
        total: 0
      };
      this.getCouponList();
      this.setLoading(false);
    });
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  }
};
</script>

<style lang="scss" scoped>
.page-mobile-coupon {
  width: 100vw;
  min-height: 100vh;
  background-color: #ffffff;
  .footer {
    padding: 0.3rem;
    font-size: 0.26rem;
    color: #babec2;
    text-align: center;
    .tips {
      position: relative;
    }
    .tips::before {
      content: "";
      display: block;
      position: absolute;
      left: -1.7rem;
      top: 50%;
      transform: translateY(-1px);
      width: 1.5rem;
      height: 1px;
      background: #babec2;
    }
    .tips::after {
      content: "";
      display: block;
      position: absolute;
      right: -1.7rem;
      top: 50%;
      width: 1.5rem;
      transform: translateY(-1px);
      height: 1px;
      background: #babec2;
    }
  }
  .menu-list{
    width: 7.2rem;
    height: .8rem;
    display: flex;
    justify-content: space-between;
    font-size: .3rem;
    .menu-item{
      text-align: center;
      line-height: .8rem;
      width: 33.333%;
      height: .8rem;
      position: relative;
    }
    .menu-item.active{
      color: var(--theme-color);
      &::before{
        content: "";
        width: 60%;
        height: .0384rem;
        display: block;
        background-color: var(--theme-color);
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translateX(-50%);
      }
    }
  }
  .coupon-list{
    width: 7.2rem;
    margin-top: .2rem;
    .coupon-box{
      width: 6.9888rem;
      height: 2.6112rem;
      margin: 0rem auto 0;
      background-size: 100% 100%;
      background-repeat: no-repeat;
      position: relative;
      display: flex;
      align-items: center;
      padding: .5rem .2rem .38rem;
      &.bg-one{
        background-image: url('/img/mobile/coupon_type1.png');
      }
      &.bg-two{
        background-image: url('/img/mobile/coupon_type2.png');
        .tags{
          color: #c88859;
        }
      }
      &.bg-three{
        background-image: url('/img/mobile/coupon_type3.png');
        .tags{
          color: #818181;
        }
      }
      .tags{
        left: .2rem;
        top: 0;
        position: absolute;
        font-weight: bold;
        width: 2.2rem;
        height: .46rem;
        line-height: .46rem;
        font-size: .24rem;
        text-align: center;
        color: #b05411;
      }
      .card-left{
        width: 30%;
        height: 1.6rem;
        text-align: center;
        line-height: 1.6rem;
        font-size: .384rem;
        color: #ffffff;
        position: relative;
        .price{
          font-size: .672rem;
        }
        .right-line{
          position: absolute;
          right: -.1rem;
          top: 50%;
          transform: translateY(-50%);
          width: .1rem;
          height: 1.3rem;
          background-image: linear-gradient(to bottom, #fff 0%, #fff 50%, transparent 50%);
          background-size: .03rem .27rem;
          background-repeat: repeat-y;
        }
      }
      .card-right{
        width: 70%;
        height: 1.6rem;
        color: #fff;
        padding-left: .3rem;
        .max-time{
          margin-top: .15rem;
          font-size: .2688rem;
          font-weight: bold;
        }
        .course-name{
          font-size: .2688rem;
          margin-top: .1rem;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        .info-time{
          margin-top: .2rem;
          font-size: .2304rem;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.page-mobile-coupon {
}
</style>
